// index.js
import request from "../../utils/request";
import config from '../../config';
const app = getApp();
Page({
  data: {
    userInfo: {},
    config: {},
    baseUrl: config.BASE_URL,
    statusBarHeight: wx.getSystemInfoSync().statusBarHeight,
    navBarHeight: wx.getSystemInfoSync().platform === 'ios' ? 44 : 48, // 默认导航栏高度
    navBarContentHeight: 0, // 导航栏内容区域高度（不含状态栏）
    menuButtonInfo: wx.getMenuButtonBoundingClientRect(), // 获取胶囊按钮信息
    swiperList: [],
    taskList: [],
    latestTasksIcon: '/assets/images/latest_tasks_icon.png', // 你需要准备这个图标 (M形状的那个)
    countdownIcon: '/assets/images/time_icon.png',
    showWarmPromptModal: false, // 控制弹窗显示，默认为false
    promptQrCodeUrl: '/assets/images/gg.png', // 替换为你的公众号二维码图片路径
    showAd: false,
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 2000,
    duration: 500,
    bannerList: [],
    hotTaskList: [],
    latestTaskList: [],
    pageNum: 1,
    pageSize: 15,
    isLoadingMore: false,
    hasMoreData: true,
    adConfig: {}
  },
  onLoad: function (options) {
    if (options.referenceId) {
      wx.setStorageSync('referenceId', options.referenceId)
    }
    // 计算导航栏内容区域高度
    const menuButtonInfo = this.data.menuButtonInfo;
    const systemInfo = wx.getSystemInfoSync();
    const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - systemInfo.statusBarHeight) * 2;
    this.setData({
      navBarHeight: navBarHeight,
      navBarContentHeight: menuButtonInfo.height // 内容区域高度可以设置为胶囊按钮高度
    });

    this.getConfig();
  },
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0 // 首页对应的 tabBar 索引是 0
      });
    }
    let token = wx.getStorageSync('token');
    if (token) {
      // 获取登录信息
      this.getLoginInfo();
    }
    // 获取配置
    this.getConfig();
    // 获取banner列表
    this.getBannerList();
    // 获取任务列表
    this.getTaskList();
  },
  // 事件处理函数
  handleTaskTap: function (event) {
    const taskId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/task-detail/task-detail?id=' + taskId
    });
  },
  handleSwiperTap: function (event) {
    const swiperId = event.currentTarget.dataset.id;
    console.log('Swiper item tapped:', swiperId);
    // 你可以在这里添加跳转逻辑，比如跳转到活动详情页
    // wx.navigateTo({ url: '/pages/activity-detail/activity-detail?id=' + swiperId });
  },
  // 关闭温馨提示弹窗
  hideWarmPromptModal: function () {
    this.setData({
      showWarmPromptModal: false
    });
  },
  getConfig: function () {
    request({
      url: 'api/login/getConfig',
    }).then(res => {
      if (res.data) {
        wx.setStorageSync('config', res.data);
        this.setData({
          config: res.data
        });
        if (res.data.logoTk && wx.getStorageSync('token') && !wx.getStorageSync('isShow')) {
          this.setData({
            showWarmPromptModal: true
          });
          wx.setStorageSync('isShow', true)
        }
      }
    });
  },
  getLoginInfo: function () {
    request({
      url: 'api/login/getLoginInfo',
      method: 'POST',
    }).then(res => {
      if (res.data) {
        wx.setStorageSync('userInfo', res.data);
        this.setData({
          userInfo: res.data
        });
      }
    });
  },
  getBannerList: function () {
    request({
      url: 'api/home/getBanner',
    }).then(res => {
      if (res.data && res.data.length > 0) {
        let swiperList = [];
        res.data.forEach(item => {
          swiperList.push({
            id: Math.random().toString(36).substring(2, 15),
            type: 'image',
            url: config.BASE_URL + item.url,
          });
        });
        this.setData({
          swiperList: swiperList
        });
      }
    });
  },
  getTaskList: function () {
    this.setData({
      taskList: []
    });
    let url = 'api/home/getNewTask'
    if (wx.getStorageSync('token') && wx.getStorageSync('userInfo')) {
      url += '?userId=' + wx.getStorageSync('userInfo').id
    }
    request({
      url,
    }).then(res => {
      if (res.rows && res.rows.length > 0) {
        res.rows.forEach(item => {
          item.countdownTime = this.getCountdownTime(item.endTime);
        });
        this.setData({
          taskList: res.rows
        });
      }
    });
  },
  // 获取倒计时时间  格式为 3天 : 21小时 : 16分钟
  getCountdownTime: function (endTime) {
    let now = new Date();
    let end = new Date(endTime);
    let diff = end - now;
    let days = Math.floor(diff / (1000 * 60 * 60 * 24));
    let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    return `${days}天 : ${hours}小时 : ${minutes}分钟`;
  },
  getTasksList: function (isLoadMore = false) {
    if (this.data.isLoadingMore) return;

    if (isLoadMore) {
      this.setData({
        isLoadingMore: true
      });
    } else {
      this.setData({
        pageNum: 1,
        latestTaskList: [],
        hasMoreData: true
      });
    }

    request({
      url: 'api/home/getTasksList',
      method: 'get',
      data: {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      }
    }).then(res => {
      if (res.code == 200 && res.rows) {
        const newTasks = isLoadMore ? this.data.latestTaskList.concat(res.rows) : res.rows;
        const currentPageSize = res.rows.length;
        this.setData({
          latestTaskList: newTasks,
          hasMoreData: currentPageSize >= this.data.pageSize,
          pageNum: this.data.pageNum + 1
        });
      } else if (res.code == 200 && (!res.rows || res.rows.length === 0)) {
        this.setData({
          hasMoreData: false
        });
      } else {
        wx.showToast({
          title: res.message || '加载任务失败',
          icon: 'none'
        });
        if (!isLoadMore) this.setData({
          latestTaskList: [],
          hasMoreData: false
        });
      }
    }).catch(err => {
      console.error('Fetch tasks error:', err);
      wx.showToast({
        title: '加载任务异常',
        icon: 'none'
      });
      if (!isLoadMore) this.setData({
        latestTaskList: [],
        hasMoreData: false
      });
    }).finally(() => {
      if (isLoadMore) this.setData({
        isLoadingMore: false
      });
      wx.stopPullDownRefresh();
    });
  },
  onReachBottom: function () {
    if (this.data.hasMoreData && !this.data.isLoadingMore) {
      this.getTasksList(true);
    }
  },
  onPullDownRefresh: function () {
    this.getConfig(); // 刷新配置（包含轮播图和热门任务）
    this.getTasksList(false); // 刷新最新任务列表
  },
  // 允许页面分享
  onShareAppMessage: function () {
    return {
      title: '邀请你加入喵集令，一起完成任务吧！',
      path: '/pages/index/index?referenceId=' + (this.data.userInfo.id || ''), // 可以带上邀请者ID
      imageUrl: '/assets/images/share_1.png' // 自定义分享图片，你需要准备这张图片
    };
  }
});